package cc.flyflow.core.listeners;

import cc.flyflow.common.constants.ProcessInstanceConstant;
import cc.flyflow.core.utils.FlowableUtils;
import cn.hutool.extra.spring.SpringUtil;
import lombok.extern.slf4j.Slf4j;
import org.flowable.engine.TaskService;
import org.flowable.task.service.delegate.DelegateTask;
import org.flowable.task.service.delegate.TaskListener;
import org.flowable.task.service.impl.persistence.entity.TaskEntityImpl;

/**
 * 审批节点 监听
 *
 * @author Jyl
 */
@Slf4j
public class ApprovalCreateListener implements TaskListener
{

    /**
     * 通知
     *
     * @param delegateTask
     */
    @Override
    public void notify(DelegateTask delegateTask)
    {
        TaskService taskService = SpringUtil.getBean(TaskService.class);
        TaskEntityImpl taskEntity = (TaskEntityImpl) delegateTask;

        String assignee = delegateTask.getAssignee();//分配到任务的人
        String name = delegateTask.getName();//任务名称
        String processInstanceId = delegateTask.getProcessInstanceId();//流程实例id

        String tenantId = taskEntity.getTenantId();//租户id
        String nodeId = taskEntity.getTaskDefinitionKey();//节点id
        String processDefinitionId = taskEntity.getProcessDefinitionId();//流程定义id
        String flowId = FlowableUtils.getFlowId(processDefinitionId, tenantId);//流程id
        String taskId = taskEntity.getId();//设置流程唯一id

        log.info("审批人创建了 任务{}-执行人:{}", name, assignee);

        taskService.setVariableLocal(
                taskId,
                ProcessInstanceConstant.VariableKey.FLOW_UNIQUE_ID,
                FlowableUtils.getFlowUniqueId(nodeId, flowId, processInstanceId, delegateTask.getTenantId())
        );
    }
}
